﻿/// <summary>
/// Implements Universe class.
/// </summary>
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace SpaceSim
{
    /// <summary>
    /// Manager class for SpaceSim.
    /// </summary>
    public class Universe
    {
        /// <summary>
        /// Manager class for SpaceSim.
        /// </summary>
        /// <param name="glossaryPath">
        /// Path to glossary.xml describing all potential AstroBodyDescs in simulation.
        /// </param>
        public Universe(string glossaryPath)
        {
            DefaultGlossary = _LoadGlossary(glossaryPath);
        }

        /// <summary>
        /// Builds a random SolarSystem and returns it to the caller.
        /// </summary>
        /// <returns>Randomly constructed SolarSystem.</returns>
        public SolarSystem BuildSolarSystem()
        {
            return new SolarSystem(DefaultGlossary);
        }

        /// <summary>
        /// Saves a SolarSystem to a file on disc
        /// </summary>
        /// <param name="fileName">Path to file to save SolarSystem specifications to.</param>
        public void SaveSolarSystem(SolarSystem solar, string fileName)
        {
            solar.XmlSerialize(fileName);
        }

        /// <summary>
        /// Loads a SolarSystem from disc
        /// </summary>
        /// <param name="fileName">Path to xml file on disc describing a SolarSystem object.</param>
        /// <returns>SolarSystem loaded from disc.</returns>
        public SolarSystem LoadSolarSystem(string fileName)
        {
            return Misc.XmlDeserialize<SpaceSim.SolarSystem>(fileName);
        }

        /// <summary>
        /// Internal helper method.
        /// 
        /// Loads glossary.xml file.
        /// </summary>
        /// <param name="glossaryPath">
        /// Path to glossary.xml describing all potential AstroBodyDescs in simulation.
        /// </param>
        /// <returns>Loaded Glossary object.</returns>
        private Glossary _LoadGlossary(string glossaryPath)
        {
            using (FileStream streamIn = new FileStream(glossaryPath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(Glossary));
                return (Glossary)serializer.Deserialize(streamIn);
            }
        }

        /// <summary>
        /// Glossary file used to construct SolarSystems.
        /// </summary>
        private Glossary DefaultGlossary { get; set; }
    }
}
